
var TiddlyAddonVersuch  = {

    //debugAppendFile: "-saved",//debug
    debugAppendFile: "",//release

    info: " save load version:{appversion} test:0 ",

    //von foxbeans
    onLoad: function() {
        // initialization code
        this.initialized = true;
        this.gfiltersimportexportBundle = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService);
        this.mystrings = this.gfiltersimportexportBundle.createBundle("chrome://{appname}/locale/overlay.properties");

    },
    //von foxbeans
    getString:function(key) //i18n
    {
        try{
            var str = this.mystrings.GetStringFromName(key);
            return str;
        }catch(e)
        {
            return key;
        }
    },
    //von foxbeans
    onMenuItemCommand: function() {
        alert(this.getString("Continue_Confirm"));
    },

    onTiddlyEvent: function(evt){
        this.setLog(evt);
        var cmd = evt.target.getAttribute("cmd");
        switch(cmd){
            case "check": this.onTiddlyCheck(evt);
                break;
            case "save": this.onTiddlySave(evt);
                break;
            case "load": this.onTiddlyLoad(evt);
                break;
            default: evt.target.setAttribute("result", "invalid command");
        }
    },
    onTiddlyCheck: function(evt){
        var url = ""+evt.target.ownerDocument.location;
        var cut = "file://";
        if(url.substr(0,cut.length) != cut) res = "no";
        else res = this.info;
        //res = " dummy-nothing " // fake result
        evt.target.setAttribute("result", res);
    },
    onTiddlySave: function(evt) {
        var from = evt.target.ownerDocument.location;
        var data = evt.target.getAttribute("data");
        var dump = evt.target.getAttribute("dump");
        evt.target.setAttribute("result", "saving");
        this.log(from + "\ndump: " + dump + "\nsaving: " + data.substring(0,100) + "\n....");
        var done = this.saveFile(from,data);
        this.log("saved: " + done);
        evt.target.setAttribute("result", "saved");
    },
    onTiddlyLoad: function(evt) {
        var from = evt.target.ownerDocument.location;
        //var data = evt.target.getAttribute("data");
        //var dump = evt.target.getAttribute("dump");
        evt.target.setAttribute("result", "loading");
        this.log("loading: " + from);
        var data = this.loadFile(from,data);
        this.log("got: " + data.substring(0,100) + "....");
        evt.target.setAttribute("data", data);
        evt.target.setAttribute("dump", "-");
        evt.target.setAttribute("result", "loaded");
    },

    // console: none
    setLog: function(evt){
        this.console = evt.target.ownerDocument.getElementById('console');
    },
    log: function(s){
        s = "addon: " + s;
        if(!this.console) {
            //alert("keine console, log: " + s);
        } else {
            s=s.split("&").join("&amp;").split( "<").join("&lt;").split(">").join("&gt;");
            this.console.innerHTML += "<br>" + s;
        }
    },
    //von Tiddly
    // Returns false if there's an error, true if it saved OK
    saveFile: function(url,content)
    {
        var filePath = this.url2File(url);
        if(!filePath) return false;
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
            file.initWithPath(filePath);
            if(!file.exists())
                file.create(0,0664);
            var out = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
            out.init(file,0x20|0x02,00004,null);
            out.write(content,content.length);
            out.flush();
            out.close();
            return true;
        } catch(ex) {
            return false;
        }
        return false;//sonst ist lint verwirrt.
    },
    // von Tiddly
    // Returns  false if there's an error, or a string of the content if successful
    loadFile: function(url){
        var filePath = this.url2File(url);
        if(!filePath) return false;
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
            file.initWithPath(filePath);
            if(!file.exists())
                return null;
            var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
            inputStream.init(file,0x01,00004,null);
            var sInputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
            sInputStream.init(inputStream);
            var contents = sInputStream.read(sInputStream.available());
            sInputStream.close();
            inputStream.close();
            return contents;
        } catch(ex) {
            return false;
        }
    },
    err: function(catched){
        alert("addon: " + catched);
        this.log("CATCHED: " + catched);
    },
    url2File: function(url){
        url = ""+url;//als string
        this.log("url: "+url);
        var cut = "file://";
        if(url.substr(0,cut.length) != cut) {
            alert("Kein lokaler Tiddly");
            return false;
        }
        return this.getLocalPath(url);
    },

    //von tiddly
    getLocalPath: function(origPath)
    {
        //- var originalPath = this.convertUriToUTF8(origPath,config.options.txtFileSystemCharSet);
        var originalPath = origPath; //ist per defautl utf8
        // Remove any location or query part of the URL
        var argPos = originalPath.indexOf("?");
        if(argPos != -1)
            originalPath = originalPath.substr(0,argPos);
        var hashPos = originalPath.indexOf("#");
        if(hashPos != -1)
            originalPath = originalPath.substr(0,hashPos);
        // Convert file://localhost/ to file:///
        if(originalPath.indexOf("file://localhost/") == 0)
            originalPath = "file://" + originalPath.substr(16);
        // Convert to a native file format
        var localPath;
        if(originalPath.charAt(9) == ":") // pc local file
            localPath = unescape(originalPath.substr(8)).replace(new RegExp("/","g"),"\\");
        else if(originalPath.indexOf("file://///") == 0) // FireFox pc network file
            localPath = "\\\\" + unescape(originalPath.substr(10)).replace(new RegExp("/","g"),"\\");
        else if(originalPath.indexOf("file:///") == 0) // mac/unix local file
            localPath = unescape(originalPath.substr(7));
        else if(originalPath.indexOf("file:/") == 0) // mac/unix local file
            localPath = unescape(originalPath.substr(5));
        else // pc network file
            localPath = "\\\\" + unescape(originalPath.substr(7)).replace(new RegExp("/","g"),"\\");
        return localPath;
    },
}

window.addEventListener("load", function(e) {
    try{
        TiddlyAddonVersuch.onLoad(e);
    }catch(e){
        TiddlyAddonVersuch.err(e);
    }
}, false);


document.addEventListener("TiddlyAddonVersuchEvent", function(e) {
    try{
        TiddlyAddonVersuch.onTiddlyEvent(e);
    }catch(e){
        TiddlyAddonVersuch.err(e);
    }

}, false, true);
